const { jwt_config } = require("../config/config");
const jwt = require("jsonwebtoken")

module.exports={
    sessionCheck:async(ctx,next)=>{
        if(!ctx.session.userName){
           ctx.session.info="账号已过期，请重新登录"
           ctx.response.redirect('/login')
        //    await ctx.render('login',{info:'账号已过期，请重新登录'})

        }else{
            await next()
        }
    },
    tokenCheck:async(ctx,next)=>{
        const {authorization = ''} = ctx.request.header;
        const token = authorization.replace('Bearer ','');
        if(authorization){
            try{
                const  payload_info = jwt.verify(token,jwt_config.secretKey);
                console.log(payload_info)
                ctx.state.userNum = payload_info.userNum;
                let iat = new Date(payload_info.iat*1000);
                let exp = new Date(payload_info.exp*1000);
                console.log(("开始时间：") + iat.getHours()+':'+iat.getMinutes()+':'+iat.getSeconds());
                console.log(("失效时间：") + exp.getHours()+':'+exp.getMinutes()+':'+exp.getSeconds());
            }catch(err){
             console.log(err);
             ctx.body = {
                success:false,
                data:{},
                info:{msg:"token验证失败"},
                code:401
             }
            }
        }else{
            ctx.body = {
                success:false,
                data:{},
                info:{msg:"未持有验证信息，非法访问"},
                code:400
            }
            return
        }
        await next()
    }
}